import { cache } from '@/utils';
import { IMG_PREFIX, HOST } from '@/utils/config';
import { ref, readonly, toRefs } from 'vue';
import { getSystemInfo } from '@tarojs/taro';

const __safeArea = {};
export const useSafeArea = () => {
  if (__safeArea.init) {
    return Promise.resolve(readonly(__safeArea));
  }
  return new Promise(resolve => {
    getSystemInfo({
      success(res) {
        const { screenWidth, screenHeight, windowHeight, statusBarHeight } = res;
        if (res.safeArea) {
          const { top, bottom, left, right, height } = res.safeArea;
          if (top + bottom + left + right == 0) {
            return;
          }
          __safeArea.init = true;
          __safeArea.head = top + 44;
          __safeArea.top = top;
          __safeArea.left = left;
          __safeArea.bottom = screenHeight - height - top;
          __safeArea.right = screenWidth - right;
          resolve(readonly(__safeArea));
        }
      }
    });
  });
};

export const builderImgUrl = src => {
  if (!src) {
    return src;
  }
  if (!/^[a-f0-9]+$/.test(src)) return src;
  return IMG_PREFIX.value + src;
};

export const builderQrcode = (path, appendId) => {
  let url = `${HOST.value}/api/customer/user/Qrcode?path=${encodeURIComponent(path)}&access_token=${encodeURIComponent(cache.get('token'))}`;
  if (appendId) {
    url += '&appendId=' + appendId;
  }
  return url;
};

export const builderAttrs = (attrs, args) => {
  for (let i = 0; i < attrs.length; i++) {
    const element = attrs[i];
    if (args[element.key]) {
      element.value = args[element.key];
    }
  }
  return attrs;
};

export const isLogin = () => {
  return !!cache.get('token');
};

export const loginDelegate = [];

export const afterLogin = () => {
  return new Promise((resolve, reject) => {
    if (isLogin()) {
      resolve();
    } else {
      loginDelegate.push(resolve);
    }
  });
};

export const anyType = def => {
  return {
    type: [Number, Object, String, Array, Boolean],
    default: def
  };
};

export const hideMobile = mobile => {
  if (!mobile) return mobile;
  return mobile.substring(0, 3) + '****' + mobile.substring(7);
};

export const timeCountdown = (time, now) => {
  let x = Math.max(time - now, 0);
  let s, m, h, d;
  s = parseInt(x % 60);
  m = parseInt(x / 60) % 60;
  h = parseInt(x / 3600) % 24;
  d = parseInt(x / 3600 / 24);
  if (s < 10) {
    s = '0' + s;
  }
  if (m < 10) {
    m = '0' + m;
  }
  if (h < 10) {
    h = '0' + h;
  }
  if (d > 0) {
    return `${d}天${h}时${m}分`;
  } else if (h > 0) {
    return `${h}时${m}分${s}秒`;
  } else {
    return `${m}分${s}秒`;
  }
};

export * from './form';

export * from './loading';

export * from './router';

export * from './pager';
